package logger

import (
	"RpcNasSync/config/serve"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
	"log"
	"os"
	"path"
)

var logger *zap.Logger

func Init(cfg *serve.Config) {
	//share.Trace = true
	encoder := InitEncoder()
	level := InitLevel(cfg.LogLevel)
	errLevel := InitLevel("error")
	writer := InitWriter(cfg.LogFile)
	c1 := zapcore.NewCore(encoder, writer, level)
	//c2 := zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), errLevel)
	dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	errFile := path.Join(dir, "rpc_sync_error.log")
	//errFile := path.Join(path.Dir(logFile), "nas_sync_error.log")
	//os.MkdirAll(path.Dir(logFile), os.ModeDir)

	errF, _ := os.OpenFile(errFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	c3 := zapcore.NewCore(encoder, zapcore.AddSync(errF), errLevel)
	//core := zapcore.NewTee(c2)
	//fmt.Println(c1, c3)
	core := zapcore.NewTee(c1, c3)
	logger = zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
	// 标准错误重定向到errF中
	os.Stderr = errF
}

func InitEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.RFC3339NanoTimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder //在日志文件中使用大写字母记录日志级别
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func InitWriter(logFile string) zapcore.WriteSyncer {
	lumberjackLogger := &lumberjack.Logger{
		Filename:   logFile, // 日志文件路径
		MaxSize:    100,     // 每个日志文件保存的最大尺寸 单位: M
		MaxBackups: 2,       // 日志文件最多保存多少个备份
		MaxAge:     30,      // 日志文件最多保存多少天
		Compress:   false,   // 是否压缩
	}
	return zapcore.AddSync(lumberjackLogger)
}

func InitLevel(level string) zapcore.LevelEnabler {
	switch level {
	case "debug":
		return zap.DebugLevel
	case "info":
		return zap.InfoLevel
	case "error":
		return zap.ErrorLevel
	default:
		return zap.InfoLevel
	}
}

// LogInfo 记录信息日志
func LogInfo(message string, fields ...zap.Field) {
	logger.Info(message, fields...)
}

func LogError(message string, fields ...zap.Field) {
	logger.Error(message, fields...)
}

// LogDebug 记录调试日志
func LogDebug(message string, fields ...zap.Field) {
	logger.Debug(message, fields...)
}
